/*
 * main.cpp
 *
 *  Created on: 2013-10-16
 *      Author: WinDDK
 */

#include "KiKernel.h"
#include "dbgcommon.h"
#ifdef __cplusplus
extern "C"
{
#endif

#define DeviceName    L"\\Device\\GameDriver"
#define DosDeviceName L"\\DosDevices\\GameDriver"

KiPE *kernelPE = NULL;

void UnloadDriver(IN PDRIVER_OBJECT pDriverObject)
{
    UNICODE_STRING symbolicLinkName;
    RtlInitUnicodeString(&symbolicLinkName, DosDeviceName);

    PDEVICE_OBJECT pDev = pDriverObject->DeviceObject;
    IoDeleteDevice(pDev);

    IoDeleteSymbolicLink(&symbolicLinkName);

    if (kernelPE != NULL)
    {
        delete kernelPE;
    }

    KiDebug("Success");
}

NTSTATUS CreateDevice(IN PDRIVER_OBJECT pDriverObject)
{
    UNICODE_STRING devName, symbolicLinkName;
    PDEVICE_OBJECT devObj;

    RtlInitUnicodeString(&devName, DeviceName);

    NTSTATUS status = IoCreateDevice(pDriverObject, 0, &devName, FILE_DEVICE_UNKNOWN, 0, TRUE, &devObj);
    if (!NT_SUCCESS(status))
    {
        if (status == STATUS_INSUFFICIENT_RESOURCES )
        {
            KiDebug("Insufficient Resources");
        }
        if (status == STATUS_OBJECT_NAME_EXISTS )
        {
            KiDebug("Object Name Exists");
        }
        if (status == STATUS_OBJECT_NAME_COLLISION )
        {
            KiDebug("Object Name Collision");
        }
        KiDebug("Create Device Failed");
        return status;
    }
    devObj->Flags |= DO_BUFFERED_IO;

    RtlInitUnicodeString(&symbolicLinkName, DosDeviceName);
    status = IoCreateSymbolicLink(&symbolicLinkName, &devName);
    if (!NT_SUCCESS(status))
    {
        KiDebug("Create Device Failed");
        IoDeleteDevice(devObj);
        return status;
    }

    return STATUS_SUCCESS ;
}

NTSTATUS DriverEntry(IN PDRIVER_OBJECT driverObject, IN PUNICODE_STRING registryPath)
{
    KiDebug("Success");

//        kernelPE = new(NonPagedPool)KiKernel();
//        kernelPE->LoadModule();
//        kernelPE->FixModule();

    driverObject->DriverUnload = UnloadDriver;

    CreateDevice(driverObject);

    return STATUS_SUCCESS ;
}

#ifdef __cplusplus
}
#endif
